<!DOCTYPE html>
<html lang="ru">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<link rel="stylesheet" href="views/lib/jquery-ui.theme.css">
	<link rel="stylesheet" href="views/lib/jqGrid460/css/ui.jqgrid.css">
</head>
<body>

		

		{{ render('/usersko/') }}	

	
	<script src="views/lib/jquery-1.11.0.min.js"></script>
	<script src="views/lib/lodash.min.js"></script>
	<script src="views/lib/knockout-3.1.0.debug.js"></script>
	<script src="views/lib/jqGrid460/js/jquery.jqGrid.src.js"></script>

	<script>

		function RowModel(data, parent){
			var self = this;
			self.parent = parent;
			self.events = {
				save : function(e){
					console.log(e);
					self.cells( _.clone(self.cells_edit()) );
					var data_send = {
						oper :"edit",
						id: self.id,
						rows:self.cells()
					}
					$.post(self.parent.url,data_send,function(resp){
						console.log(resp);
					});

					self.state.edit(false);
				},
				cancel : function(e){
					console.log(e);
					self.state.edit(false);
				},
				remove : function(e){
					console.log(e);
				},
				edit : function(e){
					console.log(e);
					var id = self.parent.currentId();
					if(self.id != id){
						var rows = _.map(self.parent.rows(), function(it){
							if(it.id === id){
								it.state.edit(false);
							}
							return it;
						});
						self.parent.rows(rows);
						self.parent.currentId(self.id);
					}
					self.cells_edit( _.clone( self.cells() ) );
					self.state.edit(true);
				}
			}	
			self.state = {
				edit:ko.observable(false)
			}		

			self.cells = ko.observable(data.cell);
			self.cells_edit = ko.observable();
			self.id = data.id;
		}

		function GenTableModel(data, name, $root){
			var self = this;
			self.rows = ko.observableArray();
			self.head = data.head;
			self.options = data.options;
			self.url = data.options.url;
			self.name = name;
			self.root = $root;
			self.currentId = ko.observable();
			_.each(data.rows, function(item){
				self.rows.push( new RowModel(item, self) );				
			});

			self.new_row = ko.observable();
			
			var new_row = {}
			_.each(self.head, function(it){	new_row[it.name]=''; });
			self.new_row( new_row );
			self.new_row_reset = ko.observable( self.new_row() );

			self.new_visible = ko.observable(false);
			self.events = {
				add:function(){

				},	
				save_new:function(){

				},
				cancel_new:function(){

				}
			}	
		}

		function ViewModel(){
			var self = this;
			self.genTable = {};
			table_classes = table_classes || {};
			
			_.forOwn(table_classes, function(val, key){
				self.genTable[key] = ko.observable( new GenTableModel(val, key, self) );
			});




			console.log(self.genTable);	

		}	

		$(function(){
			ko.applyBindings(ViewModel());
		});


	</script>
</body>
</html>